package com.myself.service;

import com.myself.entity.Permission;
import com.myself.entity.Role;
import com.myself.mapper.RoleMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Description:
 *
 * @Author: Liuzemin
 * @Date: 2020/7/10 15:52
 */
@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    RoleMapper roleMapper;

    @Override
    public Role findById(Long id) {
        return roleMapper.findById(id);
    }

    @Override
    public void create(Role role) {
        if (role.getPid() == null){
            role.setPid(0L);
        }
        roleMapper.create(role);
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteRole(id);
        roleMapper.deleteUserRole(id);
    }

    @Override
    public void update(Role role) {
        roleMapper.update(role);
    }

    @Override
    public List<Role> findAll() {
        return roleMapper.findAll();
    }

    @Override
    public void updateUserRole_Id(Role role) {
        roleMapper.updateUserRole_Id(role);
    }

    @Override
    public void deleteAllRolePermissions(Long id) {
        roleMapper.deleteAllRolePermissions(id);
    }

    @Override
    public void correlationPermissions(Long roleId, Long... permissionIds) {
//        correlationPermissions2(roleId, permissionIds);
        if(permissionIds == null || permissionIds.length == 0){
            return;
        }
        for(Long permissionId : permissionIds){
            if(!exists(roleId, permissionId)){
                roleMapper.correlationPermissions(roleId,permissionId);
            }
        }
    }

    @Override
    public List<Permission> findPermissionByRoleId(Long id) {
        return roleMapper.findPermissionByRoleId(id);
    }

    @Override
    public List<Permission> findRolePermissionByRoleId(Long id) {
        return roleMapper.findRolePermissionByRoleId(id);
    }

    /*@Override
    public void correlationPermissions2(Long roleId, Long[] permissionIds) {
        if(permissionIds == null || permissionIds.length == 0){
            return;
        }
        for(Long permissionId : permissionIds){
            if(!exists(roleId, permissionId)){
                roleMapper.correlationPermissions(roleId,permissionId);
            }
        }
    }*/


    private boolean exists(Long roleId, Long permissionId) {
        return roleMapper.exists(roleId, permissionId);
    }


}
